package com.qqs.distributed.advice;

import com.qqs.distributed.annotation.CacheAnnotationParser;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.Set;

public class AnnotationCacheAttributeSource extends AbstractCacheAttributeSource {

    private final Set<CacheAnnotationParser> cacheAnnotationParsers;

    public AnnotationCacheAttributeSource(Set<CacheAnnotationParser> cacheAnnotationParsers) {
        this.cacheAnnotationParsers = cacheAnnotationParsers;
    }

    @Override
    CacheAttribute findCacheAttribute(Method method) {
        return determineTransactionAttribute(method);
    }

    @Override
    CacheAttribute findCacheAttribute(Class<?> targetClass) {
        return determineTransactionAttribute(targetClass);
    }

    protected CacheAttribute determineTransactionAttribute(AnnotatedElement element) {
        for (CacheAnnotationParser cacheAnnotationParser : cacheAnnotationParsers) {
            CacheAttribute cacheAttribute = cacheAnnotationParser.parseCacheAnnotationParser(element);
            if (cacheAttribute != null) {
                return cacheAttribute;
            }
        }
        return null;
    }

    @Override
    public boolean isCandidateClass(Class<?> targetClass) {
        for (CacheAnnotationParser cacheAnnotationParser : cacheAnnotationParsers) {
            if (cacheAnnotationParser.isCandidateClass(targetClass)) {
                return true;
            }
        }
        return false;
    }
}
